<template>
  <div class="profile-container">
    <Form ref="formInline" inline :label-width="100" id="form1" :label-colon="true">
      <FormItem label="头像">
        <img :src="avatar == null ? defaultImg : avatar" />
      </FormItem>
      <FormItem>
        <Upload
          :action="'/api/user/' + this.uid + '/avatar'"
          :format="['jpg', 'png','jpeg']"
          :max-size="2048"
          :show-upload-list="false"
          :on-success="onSuccess"
          :on-error="onError"
        >
          <Button icon="ios-cloud-upload-outline">上传头像</Button>
        </Upload>
      </FormItem>
    </Form>
    <Form
      ref="formValidate"
      :model="formValidate"
      :rules="ruleValidate"
      :label-width="100"
      :label-colon="true"
      id="form2"
    >
      <FormItem label="姓名" prop="name">
        <Input v-model="formValidate.name" placeholder="请输入昵称，长度为2-12个字符" />
      </FormItem>

      <FormItem label="邮箱" prop="mail">
        <Input v-model="formValidate.mail" placeholder="请输入您的邮箱" />
      </FormItem>

      <FormItem label="收货地址" prop="address">
        <Row>
          <!-- vetur.validation.template 设置为false 不然会报错 -->
          <Col span="11">
            <Cascader :data="areaData" v-model="region" />
          </Col>
          <Col span="2" style="text-align: center">-</Col>
          <Col span="11">
            <Input v-model="formValidate.address" placeholder="街道信息，如：马家堡东路枫南世嘉19-2-1502" />
          </Col>
        </Row>
      </FormItem>

      <FormItem label="联系电话" prop="phone">
        <Input v-model="formValidate.phone" placeholder="收货时用的手机号" />
      </FormItem>

      <FormItem label="性别" prop="gender">
        <RadioGroup v-model="formValidate.gender">
          <Radio label="1">男</Radio>
          <Radio label="2">女</Radio>
          <Radio label="0">保密</Radio>
        </RadioGroup>
      </FormItem>

      <FormItem label="个性签名" prop="desc">
        <Input
          v-model="formValidate.desc"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 5 }"
          placeholder="随便说点什么介绍自己..."
        />
      </FormItem>
      <FormItem>
        <Button style="width:80px" type="primary" @click="handleSubmit('formValidate')">保 存</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import { regionData } from "element-china-area-data";

export default {
  name: "profile",
  props: {
    uid: String
  },
  data() {
    return {
      avatar: this.$store.state.avatar,
      user: Object,
      name: String,
      region: [],
      defaultImg: require("@/assets/img/default.png"),
      areaData: regionData,
      formValidate: {
        name: "",
        mail: "",
        address: "",
        gender: "",
        phone: "",
        desc: ""
      },
      ruleValidate: {
        name: [
          {
            required: true,
            message: "昵称不能为空",
            trigger: "blur"
          },
          {
            max: 12,
            min: 2,
            message: "昵称过长或过短",
            trigger: "change"
          }
        ],
        mail: [
          {
            required: true,
            message: "请填写邮箱",
            trigger: "blur"
          },
          { type: "email", message: "邮箱格式不正确", trigger: "change" }
        ],
        address: [
          {
            required: true,
            message: "请完整填写收货地址",
            trigger: "blur"
          }
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        phone: [
          {
            required: true,
            message: "请输入联系方式",
            trigger: "blur"
          },
          {
            len: 11,
            message: "电话长度不正确，请输入11位中国大陆手机号码",
            trigger: "change"
          }
        ],
        desc: [
          {
            type: "string",
            max: 60,
            message: "至多输入60个字符",
            trigger: "change"
          }
        ]
      }
    };
  },
  mounted() {
    this.$Spin.show();
    this.axios
      .get(`/api/user/${this.uid}`)
      .then(res => {
        this.user = res.data;
        this.formValidate.name = this.user.nickname;
        this.formValidate.mail = this.user.email;
        this.formValidate.gender = this.user.gender.toString();
        this.formValidate.phone = this.user.phone;
        this.formValidate.desc = this.user.bio;
        this.formValidate.address = JSON.parse(this.user.address).detail;
        this.region = JSON.parse(this.user.address).region;
        this.$Spin.hide();
      })
      .catch(error => {
        console.log("error :", error);
        this.$Spin.hide();
      });
  },
  methods: {
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.formValidate.fullAddress = {
            region: this.region,
            detail: this.formValidate.address
          };
          this.axios
            .post(`/api/user/${this.uid}`, this.formValidate)
            .then(res => this.$Message.success("保存成功！"))
            .catch(error => this.$Message.error("保存失败！请检查网络连接"));
        } else {
          this.$Message.error("信息填写不正确！请更正后重新提交");
        }
      });
    },
    onSuccess(response, file) {
      this.$store.commit("setAvatar", response.data);
      this.avatar = response.data;
      this.$Message.success("修改头像成功");
    },
    onError(error, file, fileList) {
      console.log("error :", error);
    }
  }
};
</script>
